import json
import matplotlib.pyplot as plt
from collections import defaultdict

# 初始化数据结构存储温度变化
motor_temperatures = defaultdict(list)

# 读取数据文件（请将文件名改为实际文件名）
filename = "temperature.txt"
with open(filename, "r") as file:
    for line_num, line in enumerate(file):
        try:
            record = json.loads(line.strip())
            motors = record["data"]["motor_state"]

            for idx, motor in enumerate(motors):
                if idx < len(motor_temperatures) or motor['temperature'] != 0:
                    motor_temperatures[idx].append(motor["temperature"])

        except (json.JSONDecodeError, KeyError) as e:
            print(f"Error processing line {line_num}: {e}")
            continue

# 过滤掉全零的温度数据
valid_motors = {
    idx: temps for idx, temps in motor_temperatures.items()
    if any(temp != 0 for temp in temps)
}

# 设置绘图参数
plt.figure(figsize=(15, 8))
colors = plt.cm.tab20.colors  # 使用预定义颜色
x_values = range(len(next(iter(valid_motors.values()))))  # 获取数据点数量

# 绘制每个有效电机的温度曲线
for idx, (motor_id, temps) in enumerate(valid_motors.items()):
    plt.plot(
        x_values,
        temps,
        color=colors[idx % len(colors)],
        linestyle="-",
        linewidth=1.5,
        label=f"Motor {motor_id}"
    )

# 添加图表元素
plt.title("Motor Temperature Changes by Index", fontsize=14)
plt.xlabel("Data Point Index", fontsize=12)
plt.ylabel("Temperature (°C)", fontsize=12)
plt.grid(True, alpha=0.3)
plt.legend(
    bbox_to_anchor=(1.05, 1),
    loc="upper left",
    borderaxespad=0.,
    fontsize=10
)

# 自动调整布局并显示
plt.tight_layout()
plt.show()